<template>
    <div class="left-sidebar"> 
        <!-- 搜索栏 -->
        <div class="search-bar"> 
            <el-input 
            placeholder="搜索聊天、联系人"
            v-model="searchQuery"
            :prefix-icon="Search"
            style="height: 30px; width: calc(100% - 40px)"
            size="small"
            />
            <el-dropdown trigger="click" @command="handleDropdownCommand" style="position: absolute; right: 12px; top: 12px;">
                <div class="dropdown-button">
                    <el-button size="small" circle :icon="Plus" style="height: 30px; width: 30px; padding: 0;"></el-button>
                </div>
                <template #dropdown>
                    <el-dropdown-menu>
                        <el-dropdown-item command="create-group" :icon="Message">发起群聊</el-dropdown-item>
                        <el-dropdown-item command="add-friend" :icon="UserFilled">添加朋友</el-dropdown-item>
                        <el-dropdown-item command="search-message" :icon="Search">搜索消息</el-dropdown-item>
                    </el-dropdown-menu>
                </template>
            </el-dropdown>
        </div>

        <!-- 标签页切换 -->
        <div class="tabs-container">
            <el-tabs v-model="activeTab" class="chat-tabs" size="small" tab-position="top" @tab-click="handleTabClick">
                <el-tab-pane label="会话" name="conversations"></el-tab-pane>
                <el-tab-pane label="联系人" name="contacts"></el-tab-pane>
                <el-tab-pane label="群组" name="groups"></el-tab-pane>
                <el-tab-pane label="账号设置" name="setting"></el-tab-pane>
            </el-tabs>
        </div>

        <!-- 内容区域 -->
        <div class="content-area"> 
            <!-- 账号设置页面 -->
            <template v-if="activeTab === 'setting'">
                <el-scrollbar height="calc(100vh - 130px)" class="settings-scrollbar">
                    <div class="settings-list">
                        <div 
                            v-for="item in settingsItems" 
                            :key="item.id"
                            class="settings-item" 
                            @click="handleSettingsClick(item.id)"
                        >
                            <div class="settings-icon">
                                <el-icon><component :is="item.icon" /></el-icon>
                            </div>
                            <div class="settings-label">{{ item.label }}</div>
                        </div>
                    </div>
                </el-scrollbar>
            </template>
            
            <!-- 其他页面显示会话列表 -->
            <template v-else>
                <el-scrollbar height="calc(100vh - 130px)">
                    <div
                        v-for="conversation in filteredItems" 
                        :key="conversation.id"
                        class="conversation-item"
                        :class="{ active: conversation.id === activeConversationId }"
                        @click="handleSelectConversation(conversation)"
                    >
                        <el-avatar :src="conversation.avatar" class="avatar" />
                        <div class="conversation-info">
                            <div class="conversation-header">
                                <div class="name">{{ conversation.name }}</div>
                                <div class="time">{{ formatFriendlyTime(conversation.lastMessageTime) }}</div>
                            </div>
                            <div class="last-message"> 
                                <span class="message-content" v-if="conversation.lastMessage">{{ getLastMessageContent(conversation) }}</span>
                                <span class="message-content" v-else-if="conversation.type === 2">{{ conversation.announcement }}</span>
                                <span class="message-content" v-else>{{ conversation.user_id }}</span>
                                <span v-if="conversation.unreadCount > 0" class="unread-count">
                                    {{ conversation.unreadCount }}
                                </span>
                            </div>
                        </div>
                    </div>
                </el-scrollbar>
            </template>
        </div>
    </div>
</template>
<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { Search, Plus, Message, UserFilled, Collection, Clock, Link, VideoCameraFilled, Files, Notebook, Message as MessageIcon, Mic, Right } from '@element-plus/icons-vue'
import { defineEmits } from 'vue'
import { formatFriendlyTime } from '@/utils/timeUtils' // 格式化时间
import chatApi from '@/api/chat'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'

// 响应式数据
const searchQuery = ref('')
const activeTab = ref('conversations')
const activeConversationId = ref(null)

// 定时器引用
let conversationsRefreshTimer = null

// 设置项数据
const settingsItems = [
  { id: 'collections', label: '全部收藏', icon: Collection },
  { id: 'history', label: '最近使用', icon: Clock },
  { id: 'links', label: '链接', icon: Link },
  { id: 'media', label: '图片与视频', icon: VideoCameraFilled },
  { id: 'notes', label: '笔记', icon: Notebook },
  { id: 'files', label: '文件', icon: Files },
  { id: 'chat-history', label: '聊天记录', icon: MessageIcon },
  { id: 'voice', label: '语音', icon: Mic },
  { id: 'loginOut', label: '退出', icon: Right }
]

// 引入 Vuex store
const store = useStore()
const router = useRouter()

// 添加状态管理
const conversations = ref([])
const contacts = ref([])
const groups = ref([])

// 添加加载状态
const loading = ref({
  conversations: false,
  contacts: false,
  groups: false,
  setting: false
})

// 添加错误状态
const errors = ref({
  conversations: null,
  contacts: null,
  groups: null,
  setting: null
})

const loadConversations = async() => {
  loading.value.conversations = true
  errors.value.conversations = null
  try {
    const response = await chatApi.getConversations()
    console.log('会话列表:', response)
    if (response && response.conversations) {
      conversations.value = response.conversations.map(item => ({
        id: item.id,
        name: item.name,
        phone: item.phone || '',
        email: item.email || '',
        announcement: item.announcement || '',
        avatar: item.avatar || `https://ui-avatars.com/api/?name=${encodeURIComponent(item.name)}&background=random`,
        lastMessageTime: item.last_message_time,
        unreadCount: item.unread_count,
        type: item.type,
        lastMessage: item.last_message
      }))
    }
    console.log('会话列表:', conversations.value)
  } catch (error) {
    errors.value.conversations = '加载会话列表失败'
    console.error('加载会话列表失败:', error)
  } finally {
    loading.value.conversations = false
  }
}

const loadContacts = async() => {
  loading.value.contacts = true
  errors.value.contacts = null
  try {
    const response = await chatApi.getContacts()
    // console.log('联系人列表:', response)
    if (response && response.friends) {
      contacts.value = response.friends.map(item => ({
        id: item.id,
        name: item.username,
        nickname: item.username,
        phone: item.phone,
        type: 1,
        email: item.email,
        user_id: item.user_id,
        avatar: item.avatar || `https://ui-avatars.com/api/?name=${encodeURIComponent(item.username)}&background=random`,
      }))
    }
  } catch (error) {
    errors.value.contacts = '加载联系人列表失败'
    console.error('加载联系人列表失败:', error)
  } finally {
    loading.value.contacts = false
  }
}

const loadGroups = async() => { 
  loading.value.groups = true
  errors.value.groups = null
  try {
    const response = await chatApi.getGroups()
    // console.log('群组列表:', response)
    if (response && response.groups) {
      groups.value = response.groups.map(item => ({
        id: item.id,
        name: item.name,
        announcement: item.announcement,
        type: 2,
        avatar: item.avatar || `https://ui-avatars.com/api/?name=${encodeURIComponent(item.name)}&background=random`,
        lastMessageTime: item.last_message_time,
        unreadCount: 0
      }))
    }
  } catch (error) {
    errors.value.groups = '加载群组列表失败'
    console.error('加载群组列表失败:', error)
  } finally {
    loading.value.groups = false
  }
}


// 刷新当前标签页数据
const refreshCurrentTab = async() => { 
  switch (activeTab.value) {
    case 'conversations':
      await loadConversations()
      break
    case 'contacts':
      await loadContacts()
      break
    case 'groups':
      await loadGroups()
      break
  }
}

// 初始化数据加载
onMounted(() => { 
  refreshCurrentTab()

  // 设置会话列表5秒自动刷新
  conversationsRefreshTimer = setInterval(() => { 
    if (activeTab.value === 'conversations') {
      loadConversations()
    }
  }, 5000)
})

// 组件卸载时清除定时器
onUnmounted(() => {
  if (conversationsRefreshTimer) {
    clearInterval(conversationsRefreshTimer)
  }
})

// 获取最后一条消息的内容
const getLastMessageContent = (item) => {
  // 修复：支持后端返回的数据结构
  if (activeTab.value === 'conversations' && item.lastMessage && item.lastMessage.content) {
    return item.lastMessage.content
  }
  return '暂无消息'
}

// 选中项处理函数
const handleSelectConversation = (item) => {
  activeConversationId.value = item.id
  // 触发事件传递值到父组件，包含类型信息
  emit('select-conversation', {
    ...item,
    type: activeTab.value,
    receiver_type: item.type
  })
}

const filteredItems = computed(() => {
  let items = []

  if (activeTab.value === 'conversations') { 
    items = conversations.value
  }
  else if (activeTab.value === 'contacts') { 
    items = contacts.value
  }
  else if (activeTab.value === 'groups') { 
    items = groups.value
  }

  if (!searchQuery.value) { 
    return items
  }

  return items.filter(item => item.name.includes(searchQuery.value))
})

// 处理设置项点击
const handleSettingsClick = (item) => {
  console.log('点击了设置项:', item)
  if (item === 'loginOut') {
    // 退出登录的逻辑,使用状态管理中的logout方法进行退出处理
    store.dispatch('logout')
  }
  // 可以通过emit向父组件发送事件
  emit('settings-click', item)
}

// 标签点击处理
const handleTabClick = (pane) => {
  searchQuery.value = ''
  activeConversationId.value = null
  activeTab.value = pane.props.name

  // 点击标签页时，如果对应数据为空，则加载数据
  if (
    (activeTab.value === 'conversations' && conversations.value.length === 0) ||
    (activeTab.value === 'contacts') ||
    (activeTab.value === 'groups')
  ) {
    refreshCurrentTab()
  }
}

// 处理下拉菜单命令
const handleDropdownCommand = (command) => {
  console.log('Dropdown command:', command)
  switch (command) {
    case 'create-group':
      // 发起群聊的逻辑
      console.log('发起群聊')
      // 可以通过emit向父组件发送事件
      emit('create-group')
      break
    case 'add-friend':
      // 添加朋友的逻辑
      console.log('添加朋友')
      // 可以通过emit向父组件发送事件
      emit('add-friend')
      break
    case 'search-message':
      // 路由跳转到消息搜索页面
      router.push('/messageSearch')
      break
  }
}

// 定义emits 事件，用来父组件调用这里的子组件中的变量或者方法
const emit = defineEmits(['select-conversation', 'create-group', 'add-friend', 'settings-click'])  // 这里获取的是对应选择的id的对话的数据
</script>

<style scoped>
.left-sidebar {
  width: 300px;
  background-color: #f7f8fa;
  border-right: 1px solid #e5e6eb;
  display: flex;
  flex-direction: column;
}

.search-bar {
  padding: 12px;
  position: relative;
  display: flex;
  align-items: center;
}

.dropdown-button {
  cursor: pointer;
}
.tabs-container {
  display: flex;
  justify-content: center;
  align-items: center;
  border-bottom: 1px solid #e5e6eb;
  padding: 0 12px;
}

.chat-tabs {
  width: auto;
  min-width: 240px;
  max-width: 100%;
}

.content-area {
  flex: 1;
  overflow: hidden;
}

.settings-scrollbar {
  height: 100%;
}

.settings-list {
  padding: 10px 0;
}

.settings-item {
  display: flex;
  align-items: center;
  padding: 12px 20px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.settings-item:hover {
  background-color: #f0f0f0;
}

.settings-icon {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-color: #f7f8fa;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16px;
  color: #666;
  font-size: 20px;
}

.settings-label {
  font-size: 16px;
  color: #333;
}

.conversation-item {
  display: flex;
  padding: 12px 16px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.conversation-item:hover {
  background-color: #f0f0f0;
}

.conversation-item.active {
  background-color: #e9f5ff;
}

.avatar {
  width: 48px;
  height: 48px;
  margin-right: 12px;
}

.conversation-info {
  flex: 1;
  min-width: 0;
}

.conversation-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 4px;
}

.name {
  font-weight: 500;
  color: #333;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.time {
  font-size: 12px;
  color: #999;
}

.last-message {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.message-content {
  font-size: 14px;
  color: #666;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  flex: 1;
}

.unread-count {
  background-color: #ff4d4f;
  color: white;
  font-size: 12px;
  width: 20px;
  height: 20px;
  border-radius: 50%;
  display: inline-flex;
  justify-content: center;
  align-items: center;
  margin-left: 4px;
}
</style>